package com.lgit.Model4.hw05;

import java.io.*;
import java.net.Socket;
import java.util.List;

public class ServerThread implements Runnable {

    public ServerThread() {
    }

    public ServerThread(Socket s, List<Socket> list) {
        this.s = s;
        this.list = list;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }
    Socket s = null;
    String userName;
    List<Socket> list = null;
    BufferedReader br = null;
    PrintStream ps = null;
    @Override
    public void run() {
        try {
            if (!s.isClosed()) {
                br = new BufferedReader(new InputStreamReader(s.getInputStream()));
                ServerThread st = new ServerThread();
                st.setUserName(br.readLine());
                System.out.println(st.getUserName() + "进入聊天室");
                while (true) {
                    String s1 = br.readLine();
                    System.out.println(st.getUserName() + ": " + s1);
                    if ("bye".equalsIgnoreCase(s1)) {
                        System.out.println(st.getUserName() + "已下线");
                        //s.close();
                        break;
                    }
                    for (Socket skt : list) {
                        if ("发送文件".equals(s1)) {
                            String fileName = br.readLine();
                            BufferedInputStream bis = new BufferedInputStream(new FileInputStream("src/com/lgit/Model4/hw05/TestFile/" + fileName));
                            BufferedOutputStream bos = new BufferedOutputStream(skt.getOutputStream());
                            byte[] brr = new byte[1024];
                            int res = 0;
                            while ((res = bis.read(brr)) != -1) {
                                bos.write(brr, 0, res);
                                bos.flush();
                            }
                            ps.println(st.getUserName() + "分享了文件: " + fileName);
                            break;
                        } else {
                            ps = new PrintStream(skt.getOutputStream());
                            ps.println(st.getUserName() + ": " + s1);
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != s) {
                try {
                    s.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
